package executors

import org.hibernate.{Session, SessionFactory}
import org.hibernate.cfg.Configuration
import db.Folder
import db.Client
import client_updater.ClientsUpdater
import client_updater.Update
import db.FolderManager
import objects.File1
import scala.actors.Actor

/**
 * Processes an update about a folder that was deleted in a client's dropbox.<br>
 * communicates with the database and sends updates for other clients.
 */
class DeletedFolderExecutor extends Actor{
  
  /**
   * the acting method of the actor
   */
  override def act(){
    loop{
      react{
        case (deletedFolder : File1)=> execute(deletedFolder)
        case "Quit" => exit()
        case _ => println("DeletedFolderExecutor received unknown message")
      }
    }
  }
  
  /**
   * receives a File1 that contains details about a folder that was deleted in a client's dropbox.<br>
   * communicates with the database and the disk, and sends updates for other clients.<br>
   * @param - deletedFolder : File1, details about the deleted folder
   */
  private def execute(deletedFolder: File1) {
	val cfg = new Configuration()
    var sessionFactory = null.asInstanceOf[SessionFactory]
    var session = null.asInstanceOf[Session]
    try{
    sessionFactory = cfg.configure().buildSessionFactory()
    session = sessionFactory.openSession()
    var query = session.createQuery("from Folder f where f.folderName = '" +
    								deletedFolder.name + "' and userID = " +
    								deletedFolder.uid + " and parentFolder = " +
    								deletedFolder.parent)
    val folder = query.list().get(0).asInstanceOf[Folder]
    val folderManager = new FolderManager(session)
    folderManager.deleteFolder(folder)
    query = session.createQuery("from Client c where c.userID = " + deletedFolder.uid)
    val clients = query.list().toArray
    val client = new Client
    client.setUserID(deletedFolder.uid)
    client.setClientID(deletedFolder.cid)
    //updating all relevant clients
    for( c <- clients ){
      if (c.asInstanceOf[Client] != client) {
        ClientsUpdater.addUpdate(c.asInstanceOf[Client].getClientID, new Update("deletedFolder", folder.getFolderName, 
        															folder.getParentFolder))
      }
    }
    /*clients.foreach(c => {
      if (c != client) {
        ClientsUpdater.addUpdate(c, new Update("DeletedFolder", folder.getFolderName, folder.getParent))
      }
    })*/
    session.flush
    } catch { case (e : Exception) => println(e.printStackTrace) }
  }  
}
